package com.example.healthcode2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
//登录界面Activity
public class indexActivity extends AppCompatActivity {

    private EditText edit_name, edit_pawd;
    private static final int SIGN_OK = 1;
    private static final int SIGN_NO = 2;
    private static final int SIGN_ERROR = 3;
    private static final int SIGN_OK_NODATA = 4;
    private static final int OTHER = 0;
    private String name, password;
    private Dialog dialogLoading;//登录loading的dialog
    private Button button_sign;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        edit_name = findViewById(R.id.index_editText);
        edit_pawd = findViewById(R.id.index_editText2);
        button_sign = findViewById(R.id.index_btn_sign);


    }


    @Override
    protected void onResume() {
        super.onResume();


    }

    public void indexRegisterClick(View view) {
        Intent it = new Intent(this, registerActivity.class);
        startActivity(it);
    }

    public void signClick(View view) {
        name = edit_name.getText().toString();
        password = edit_pawd.getText().toString();

        if (name.isEmpty() || password.isEmpty()) {
            dialogshow("你还没有输入账号和密码。");
            return;
        }
        button_sign.setEnabled(false);//让按钮失效
        dialogLoadingshow();//弹出loading对话框
        HttpRequest();//发送网络请求
    }

    private void HttpRequest() {
        final RequestQueue queue = Volley.newRequestQueue(indexActivity.this);
        String url = "http://30r97104b2.qicp.vip/user/login";
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        if ("success".equals(s)) {
                            myHandler.sendEmptyMessage(SIGN_OK);
                        } else if ("error".equals(s)) {
                            myHandler.sendEmptyMessage(SIGN_NO);
                        } else if ("fill".equals(s)) {
                            myHandler.sendEmptyMessage(SIGN_OK_NODATA);
                        } else {
                            myHandler.sendEmptyMessage(OTHER);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        myHandler.sendEmptyMessage(SIGN_ERROR);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", name);
                params.put("password", password);
                return params;
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);//延时发送
                    queue.add(request);//发送请求
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SIGN_OK://登录成功
                    button_sign.setEnabled(true);//按钮重新生效
                    dialogLoading.dismiss();//loading对话框关闭
                    try {
                        writefile("name.txt", name);//写入文件
                        writefile("password.txt", password);//写入文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(indexActivity.this, MainActivity.class);
                    intent.putExtra("name", name);
                    startActivity(intent);
                    finish();
                    break;
                case SIGN_OK_NODATA://登录成功但用户还没有填报数据
                    button_sign.setEnabled(true);//按钮重新生效
                    dialogLoading.dismiss();//loading对话框关闭
                    Intent it = new Intent(indexActivity.this, fillinfoActivity.class);
                    it.putExtra("name", name);
                    startActivity(it);
                    finish();
                    break;
                case SIGN_NO://登录失败 密码错误
                    button_sign.setEnabled(true);
                    dialogLoading.dismiss();
                    dialogshow("密码错误,请重新输入");//弹出对话框
                    break;
                case SIGN_ERROR://请求错误
                    button_sign.setEnabled(true);
                    dialogLoading.dismiss();
                    dialogshow("登录失败，请检查网络");
                    break;
                case OTHER://返回其他请求码
                    Toast.makeText(indexActivity.this, "网络出现未知错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //写入文件
    public void writefile(String filename, String text) throws IOException {
        System.out.println("filename:" + filename + " text:" + text);
        OutputStream out = openFileOutput(filename, Context.MODE_PRIVATE);//覆盖
        byte[] bytes = text.getBytes();
        out.write(bytes, 0, bytes.length);
        out.close();
    }

    //登录加载对话框
    private void dialogLoadingshow() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null);
        dialogLoading = new AlertDialog.Builder(this, R.style.LoadingDialog).setView(view).create();
        ImageView imageView = view.findViewById(R.id.dialog_img_loading);
        Glide.with(this).load(R.drawable.load_0_gif).into(imageView);
        dialogLoading.show();
        Window window = dialogLoading.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.9 * screenWidth);
        params.y = (int) (0.05 * screenHeight);
        window.setAttributes(params);
        window.setGravity(Gravity.TOP);
    }

    //登录对话框
    private void dialogshow(String s) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_sign, null);
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialog).setView(view).create();
        TextView textView = view.findViewById(R.id.dialog_text_sign1);
        textView.setText(s);
        Button button = view.findViewById(R.id.dialog_btn_sign);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);
        window.setAttributes(params);
    }


}
